// fetch 是一种现代通用的方法，旧浏览器可能不支持
// let promise = fetch(url, [options])

let url = 'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits';
let response = await fetch(url)
if (response.ok) {

  console.log(`content-type: ${response.headers.get('content-type')}`);

  const res = await response.json()
  // console.log(res);
}

// 下载进度 body
{
  // 1. 请求
  let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');

  // 2. 数据流读取器
  const reader = response.body.getReader()

  // 3. 获取响应头中的 content-length 需要服务器在响应头中设置
  const contentLength = +response.headers.get('Content-Length')

  // 4. 从数据流中分块读取
  let receivedLength = 0
  let chunks = []
  while (true) {
    const { done, value } = await reader.read()
    
    if (done) {
      break
    }

    chunks.push(value)
    receivedLength += value.length
    console.log(`Received ${receivedLength} of ${contentLength}`);
  }

  // 5. 合并数据块
  let chunksAll = new Uint8Array(receivedLength)
  let position = 0
  for (const chunk of chunks) {
    chunksAll.set(chunk, position)
    position += chunk.length
  }

  // 6. 解码
  let result = new TextDecoder('utf-8').decode(chunksAll)
  try {
    console.log(JSON.parse(result));
  } catch (error) {
   console.log(error);
  }
}